package com.ccit.springbootlaw.interceptors;

import com.ccit.springbootlaw.utils.JWTutil;
import com.ccit.springbootlaw.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    public StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        // 校验 token 是否为空
        if (token == null || token.isEmpty()) {
            response.setStatus(401);
            return false;
        }

        // 从 Redis 中获取 token 对应的值
        String tokenRedis = stringRedisTemplate.opsForValue().get(token);

        // 校验 Redis 中的值是否为空
        if (tokenRedis == null || tokenRedis.isEmpty()) {
            response.setStatus(401);
            return false;
        }

        try {
            Map<String, Object> claims = JWTutil.verifyToken(token);
            ThreadLocalUtil.set(claims);
            return true;
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
